package com.example.demo.test;/**
 * Created by kete on 2018-12-03.
 */

import com.alibaba.fastjson.JSONObject;
import com.google.common.io.Files;
import org.apache.ibatis.session.SqlSession;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import static com.example.demo.test.MybatisUtil.SERVER_URL;
import static java.lang.System.err;

/**
 * 作者：kete
 * 创建时间：2018-12-03 15:14
 * 功能描述：
 * 版本：
 */
public class UrlTask implements Runnable {


    private String accountNum;

    public UrlTask(String accountNum) {

        this.accountNum = accountNum;
    }

    @Override
    public void run() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        TempUrlMapper mapper = sqlSession.getMapper(TempUrlMapper.class);

        List<TempUrl> list = mapper.queryList(accountNum);
        list.forEach(model->{
            try {
                String msg = HttpClientUtil.me().httpPost(SERVER_URL,model.getAccountNo(),model.getDt());
                JSONObject msgJson = JSONObject.parseObject(msg);
                JSONObject respJson =  JSONObject.parseObject((CryptAesUtil.decrypt(msgJson.getString("msg"))));
                model.setNewUrl(respJson.getString("url"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        sqlSession.close();


        File file = new File("d:\\temp\\test"+accountNum+".txt");


        try
        {
            Files.write(JSONObject.toJSONString(list).getBytes(Charset.forName("UTF-8")), file);
        }
        catch (IOException fileIoEx)
        {
            err.println(  "ERROR trying to write to file '" + file.getName() + "' - "
                    + fileIoEx.toString());
        }

//        mapper.updateBatch(list);


        System.out.println("线程"+accountNum+"-----------更新完成");


    }
}
